<head>
  <meta charset="utf8">
</head>
<body>
  <div>
    <label for="name">姓名</label>
    <input id="name">
  </div>
  <div>
    <label for="gender">性别</label>
    <!--<input id="gender">-->
    <select id="gender">
      <option value="male">男</option>
      <option value="female">女</option>
    </select>
  </div>
  <div>
    <label for="phone">电话</label>
    <input id="phone">
  </div>
  <div>
    <button id="submit">提交</button>
  </div>

</body>

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

<script>
let id = new URLSearchParams(location.search).get('id')
//console.log('id'+id)
if(id != null){
  //let id = new URLSearchParams(location.search).get('id')
  axios.get('/user?id=' + id).then(function(res) {
    res = res.data
    document.getElementById('name').value = res.data.name
    document.getElementById('gender').value = res.data.gender
    document.getElementById('phone').value = res.data.phone
  })
}
function E(id) { // 封装
  return document.getElementById(id)
}
function V(id) {
  return E(id).value
}
// json 格式
E('submit').onclick = function() {
  let data = {
    name: V('name'),
    gender: V('gender'),
    phone: V('phone')
  }
  if(location.search != '')
    data.id = new URLSearchParams(location.search).get('id')
  axios[(location.search == '')?'post':'put']('/user',data).
  then( function(res) {
    res = res.data
    if(res.code == 0) {
      alert('操作成功')
      location.href = './index.html'
    }
    else
      alert('操作失败')
  })
}
</script>
